// pages/ai/ai.js

var that = '';
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadingStatus:false,
    beginImg:'/images/katong2.png',
    data_access_token:'',
    imgBase64:"",
    img: '',
    imgB64: '',
    content: '',
    ishow: false,
    circleList: [],
    colorCircleFirst: '#FFDF2F',
    colorCircleSecond: '#FE4D32',
  },
  getAccessToken(){
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=igEZArYsxvrUNagqMbI8y0dV&client_secret=72SFAKc9r5ihhMI5BGrxCTlCOYYxDMoi& ',
      success:res=>{
        console.log(res);
        if (res.statusCode !== 200) {
          wx.showToast({
            title: '鉴权失败',
            icon:'none'
          })
          return;
        }else{
          wx.showToast({
            title: '鉴权成功',
          })
          //重置acess_token
          this.setData({
            data_access_token:res.data.access_token
          })
         
        }
  
      }
      
  
    })
  
  },
  //选择图片
  selectImg(){
  wx.chooseImage({
    count: 0,
    sizeType:['original'],
    sourceType:['album','camera'],
    success:res=>{
      
   console.log(res.tempFilePaths[0]);
   //缓存区的连接传过去
   this.transformBase64(res.tempFilePaths[0]);
    }
  })
  
  },
  
   //图片转化为base64编码并展示
   transformBase64(imgSrc){
    var FileSystemManager = wx.getFileSystemManager();
    // 创建文件管理器
    FileSystemManager.readFile({
      filePath:imgSrc,
          encoding:'base64',
      success:res=>{
        console.log(res.data);
        this.setData({
          beginImg:'data:image/png;base64,'+res.data,
          imgBase64:res.data
        })
  
      }
    })
  
  
  },
  
  testBeauty(){
    this.setData({loadingStatus:true})
    console.log(this.data.data_access_token);
    wx.request({
      method:"POST",
      url: "https://aip.baidubce.com/rest/2.0/face/v3/detect",
      
      data:{
        access_token:this.data.data_access_token,
        face_field:'age,beauty,gender',
        image_type:'BASE64',
        image: this.data.imgBase64,
        max_face_num:1
      },
      header:{'Content-Type':'application/x-www-form-urlencoded'},
    
      success:res=>{
        console.log(res)
        if(res.data.error_code == 222202 ) {
  return wx.showToast({
    title: '检测失败，没有人脸',
    icon:'none'
  })
        }else if(res.data.error_code!==0){
         return wx.showToast({
          title:'检测失败，请检测图片',
          icon:'none'
  
         })
        }else if(res.data.error_code==0)
        {
           this.setData({loadingStatus:false})
           var genderValue=res.data.result.face_list[0].gender.type;
           var gender=(genderValue=="male")?'小哥哥':'小姐姐';
           var age=res.data.result.face_list[0].age;
           var beauty= res.data.result.face_list[0].beauty;
           console.log(gender,age,beauty);
           var that=this;
           wx.showModal({
             title: '检测结果',
             content:'您好'+gender+','+age+'岁的颜值为'+beauty,
             showCancel:false,
             confirmText:'已经知晓',
            confirmColor:'#7c160',
             success(){
               //将图片还原
               that.setData({
                 beginImg:'/assets/imgs/yz.gif',
                 imgBase64:''
               })
             }
           })
  
  
        }
  
  
      }
  
    })
  
  
  },
  onLaunch() {
    let self = this;
    wx.getSystemInfo({
        success: function (res) {
            self.globalData.screenWidth = res.windowWidth;
            self.globalData.screenHeight = res.windowHeight;
        }
    });
},
globalData: {
    screenWidth: null,
    screenHeight: null
},
  AIrecognize: function () {
    // 1. 让用户选择media
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log(res.tempFiles[0].tempFilePath)
        console.log(res.tempFiles[0].size)
        // 2. 带着用户给的图片跳转到cv页面
        wx.navigateTo({
          url: '/pages/cv/cv?user_image='+res.tempFiles[0].tempFilePath,
        })
      }
    })


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAccessToken();
    that = this;
    var leftCircle = 7.5;
    var topCircle = 7.5;
    var circleList = [];
    for (var i = 0; i < 24; i++) {
      if (i == 0) {
        topCircle = 15;
        leftCircle = 15;
      } else if (i < 6) {
        topCircle = 7.5;
        leftCircle = leftCircle + 102.5;
      } else if (i == 6) {
        topCircle = 15
        leftCircle = 620;
      } else if (i < 12) {
        topCircle = topCircle + 94;
        leftCircle = 620;
      } else if (i == 12) {
        topCircle = 565;
        leftCircle = 620;
      } else if (i < 18) {
        topCircle = 570;
        leftCircle = leftCircle - 102.5;
      } else if (i == 18) {
        topCircle = 565;
        leftCircle = 15;
      } else if (i < 24) {
        topCircle = topCircle - 94;
        leftCircle = 7.5;
      } else {
        return
      }
      circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
    }
    that.setData({
      circleList: circleList
    })
  },
  twinkle:function(){
    setInterval(function () {
      if (that.data.colorCircleFirst == '#FFDF2F') {
        that.setData({
          colorCircleFirst: '#FE4D32',
          colorCircleSecond: '#FFDF2F',
        })
      } else {
        that.setData({
          colorCircleFirst: '#FFDF2F',
          colorCircleSecond: '#FE4D32',
        })
      }
    }, 500)
  },
  chooseImg: function () {
    that.setData({
      ishow: false,
      content: ''
    });
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        that.getB64ByUrl(tempFilePaths);
        that.setData({
          img: tempFilePaths
        });
      }
    })
  },
  getB64ByUrl: function (url) {
    const FileSystemManager = wx.getFileSystemManager();
    FileSystemManager.readFile({
      filePath: url,
      encoding: 'base64',
      success(res) {
        that.setData({
          imgB64: res.data
        });
      }
    })
  },
  
  foodTap: function (e) {
    const imgB64 = that.data.imgB64;
    if (!imgB64) {
      wx.showToast({
        title: '请上传图片',
      })
      return;
    };
    that.twinkle()
    that.getToken(function (token) {
      that.getResult(token);
    });
  },
  getToken: function (callback) {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=kHRy4WbcvvnnCX8yicEpxzGS&client_secret=PC1MLhZ8ca3KFPwsUes02OwfhSNo8oUf',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      success(res) {
        var token = res.data.access_token;
        return callback(token);
      }
    });
  },
  getResult: function (token) {
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + token,
      method: "post",
      data: {
        image: that.data.imgB64,
        baike_num: 1,
        top_num: 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        that.setData({
          dishName: res.data.result[0].name,
          calorie: res.data.result[0].calorie,
          probability: res.data.result[0].probability,
          description: res.data.result[0].baike_info.description,
          image_url: res.data.result[0].baike_info.image_url,                    baike_url: res.data.result[0].baike_info.baike_url
        });
        wx.showModal({
          title: '菜品为' +that.data.dishName,
          content: '热量为' + that.data.calorie+'是否查看详情',
          success(res){
            if (res.confirm) {
              that.setData({ishow:true}) 
            }
            else{
              return
            }
          }
          
        })
       
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})